package com.example.netty.normal.string.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author xin
 * @version 2023/11/2 16:39
 **/
public class NormalStringServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(NormalStringServerHandler.class);


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.debug("收到客户端消息");
        try {
//          NormalStringClientInitializer 中的 encoder
//            NormalStringServerInitializer 中的 decoder   StringDecoder 将字节转成了 字符串，可看源码
//
            String body = (String) msg;
            System.out.println("-----server start------| " + body + " | ------server end------");

            //发送给客户端
//            服务端向客户端发送消息，采用 字符串 编码方式，对应 NormalStringServerInitializer 中的 encoder
//            NormalStringClientInitializer 中的decoder
            String serverMsg = "++++++++我是服务端给客户端的消息+++++++";
            ctx.channel().writeAndFlush(serverMsg);
        } catch (Exception e) {
            logger.error("接收数据异常", e);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
